import global from "./global";
import request from "./request";
import { getAppIDInfo } from "../config/template";
import ServiceInfoManager from "./ServiceInfoManager";

const config = getAppIDInfo();

export default async function openApiRequest(
  url: string,
  options: IRequestOptions,
  withToken = true
) {
  const appID = config.appId;

  const requestOptions = { ...options };
  const headers: IRequestHeaders = requestOptions.notAppId
    ? {
        "Content-Type": "application/json",
      }
    : {
        "Content-Type": "application/json",
        "X-Gizwits-Application-Id": appID,
      };

  if (withToken) {
    headers["X-Gizwits-User-token"] = global.token;
  }

  requestOptions.headers = { ...headers, ...options.headers };
  requestOptions.data = requestOptions.body
  console.log(`openApi request ${url}`, requestOptions.headers);
  const openApiUrl = await ServiceInfoManager.getOpenApiUrl();
  return request(openApiUrl + url, requestOptions);
}

export async function statisticRequest(
  url: string,
  options: IRequestOptions,
  withToken = true
) {
  const appID = config.appId;
  const requestOptions = { ...options, data: options.body };
  const headers: IRequestHeaders = {
    "Content-Type": "application/json",
    "X-Gizwits-Application-Id": appID,
  };

  if (withToken) {
    headers["X-Gizwits-User-token"] = global.token;
  }

  requestOptions.headers = { ...headers, ...options.headers };
  const baseUrl = `https://api.gizwits.com/`;
  console.log("===statisticRequest===", baseUrl + url, requestOptions);
  
  return request(baseUrl + url, requestOptions);
}
